<script setup lang="ts">
import { setup } from "@/utils/setup.js";
import { usePrevious } from "@vueuse/core";
import {
  NButtonGroup,
  NAlert,
  NCard,
  NGrid,
  NGridItem,
  NNumberAnimation,
  NStatistic,
  NButton,
} from "naive-ui";
import { computed } from "vue";

const { configStore, storageStore, errorHandler } = setup();
const repositoryUrl = "https://gitee.com/idnewnil2/ohmydev";

const ids = computed(() => ({
  valid: storageStore.ids.value?.valid.length ?? 0,
  invalid: storageStore.ids.value?.invalid.length ?? 0,
}));
const previousIds = usePrevious(ids, { valid: 0, invalid: 0 });
</script>

<template>
  <NAlert style="margin: 8px 16px 0 8px" type="info">
    欢迎使用 OhMyDev，仓库地址：
    <a :href="repositoryUrl">{{ repositoryUrl }}</a>
  </NAlert>
  <div style="padding: 16px 32px 16px 16px">
    <NGrid :x-gap="16" :y-gap="12">
      <NGridItem :span="12">
        <NCard size="small" title="清理空间" hoverable>
          <template #header-extra>
            <NButtonGroup>
              <NButton
                :disabled="
                  configStore.config === undefined ||
                  storageStore.ids.state.loading
                "
                @click="storageStore.fetchIds().catch(errorHandler)"
              >
                检测
              </NButton>
              <NButton
                :disabled="!storageStore.ids.state.ready"
                @click="storageStore.gc().catch(errorHandler)"
              >
                清理
              </NButton>
            </NButtonGroup>
          </template>
          <NGrid :x-gap="16" :y-gap="12">
            <NGridItem :span="12">
              <NCard size="small" embedded hoverable>
                <NStatistic label="有效存储区域" tabular-nums>
                  <template v-if="storageStore.ids.state.new">-</template>
                  <NNumberAnimation
                    v-else
                    :from="previousIds.valid"
                    :to="ids.valid"
                  />
                </NStatistic>
              </NCard>
            </NGridItem>
            <NGridItem :span="12">
              <NCard size="small" embedded hoverable>
                <NStatistic label="无效存储区域" tabular-nums>
                  <template v-if="storageStore.ids.state.new">-</template>
                  <NNumberAnimation
                    v-else
                    :from="previousIds.invalid"
                    :to="ids.invalid"
                  />
                </NStatistic>
              </NCard>
            </NGridItem>
          </NGrid>
        </NCard>
      </NGridItem>
    </NGrid>
  </div>
</template>
